package backendimpl

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/astaxie/beego"
	"github.com/opensourceways/server-common-lib/utils"
)

const (
	statusFixed = "Fixed"
)

func NewBackendImpl() backendImpl {
	return backendImpl{
		client: utils.NewHttpClient(3),
	}
}

type backendImpl struct {
	client utils.HttpClient
}

type Response struct {
	Result []Result `json:"result"`
}

type Result struct {
	CveId       string `json:"cveId"`
	PackageName string `json:"packageName"`
	ProductName string `json:"productName"`
	Status      string `json:"status"`
}

func (r Result) IsFixed() bool {
	return r.Status == statusFixed
}

func (impl backendImpl) PublishedInfo(cveNum, packageName string) ([]string, error) {
	url := fmt.Sprintf("%s/api-cve/cve-security-notice-server/cvedatabase/getCVEProductPackageList?cveId=%s&packageName=%s",
		beego.AppConfig.String("reflink::openeuler_web"), cveNum, packageName,
	)

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}

	data, _, err := impl.client.Download(req)
	if err != nil {
		return nil, err
	}

	var v Response
	if err = json.Unmarshal(data, &v); err != nil {
		return nil, err
	}

	var ret []string
	for _, item := range v.Result {
		if item.IsFixed() {
			ret = append(ret, item.ProductName)
		}
	}

	return ret, nil
}
